package com.devplatform.service.impl.points;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.points.OrderMapper;
import com.devplatform.pojo.points.Order;
import com.devplatform.pojo.points.OrderVo;
import com.devplatform.pojo.points.PointsMall;
import com.devplatform.pojo.points.UserPoints;
import com.devplatform.pojo.user.User;
import com.devplatform.service.impl.UserService;
import com.devplatform.service.points.OrderService;
import com.devplatform.service.points.PointsCommonService;
import com.devplatform.service.points.PointsMallService;
import com.devplatform.service.points.UserPointsService;
import com.devplatform.util.MessageUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author 86156
 * @description 针对表【order】的数据库操作Service实现
 * @createDate 2025-09-28 11:26:04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserService userService;
    @Resource
    private UserPointsService userPointsService;
    @Resource
    private PointsCommonService pointsCommonService;
    @Resource
    private PointsMallService pointsMallService;
    @Resource
    private MessageUtil messageUtil;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(Long userId, Integer goodsId) {
        // 1. 仅查询一次用户信息，后续直接复用
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 2. 检查商品（仅查询一次）
        PointsMall pointsMall = pointsMallService.getById(goodsId);
        if (pointsMall == null) {
            throw new RuntimeException("商品不存在");
        }
        if (pointsMall.getStatus() != 1 || pointsMall.getStock() <= 0) {
            throw new RuntimeException("商品不可兑换（已下架或库存不足）");
        }

        // 3. 校验用户等级（直接从已查询的user对象获取，无需再次查库）
        if (user.getLevel() < pointsMall.getLevelLimit()) { // 复用user对象
            throw new RuntimeException("等级不足，无法兑换");
        }

        // 4. 校验积分（仅查询一次用户积分）
        UserPoints userPoints = userPointsService.getByUserId(userId);
        if (userPoints == null) {
            throw new RuntimeException("用户未查询到积分记录");
        }
        int pointsNeeded = pointsMall.getPointsNeeded();
        if (pointsNeeded <= 0) {
            throw new RuntimeException("商品积分设置错误");
        }
        if (userPoints.getPoints() < pointsNeeded) {
            throw new RuntimeException("积分不足，无法兑换");
        }

        // 5. 扣减积分（复用userPoints和pointsMall对象，避免再次查库）
        pointsCommonService.updatePointsDetail(userId, "EXCHANGE_GOODS", -pointsNeeded, false);
        // 优化：扣减库存时直接使用已查询的pointsMall对象，避免再次查库
        pointsMallService.removeStock(pointsMall); // 修改方法参数为PointsMall

        // 6. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setGoodsId(goodsId);
        order.setPointsUsed(pointsNeeded);
        order.setOrderStatus(0);
        order.setOrderTime(LocalDateTime.now());
        orderMapper.insert(order);
        messageUtil.sendExchangeMessage(userId, pointsMall.getGoodsName(), pointsNeeded, order.getOrderId().toString());

        return order;

    }

    @Override
    public Page<OrderVo> getOrderWithGoodsName(Page<?> page, Long userId) {
        return baseMapper.getOrderWithGoodsName(page, userId);
    }
}




